<template>
  <div class="app-container">
    <el-row>
      <el-button type="primary" style="float: right; margin-top: -5px" @click="goBack" size="">返回</el-button>
    </el-row>

    <el-row :gutter="24">
      <!-- 编辑区调整为16列 -->
      <el-col :span="16">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="新闻标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入新闻标题" />
          </el-form-item>

          <el-form-item label="作者" prop="author">
            <el-input v-model="form.author" disabled placeholder="请输入作者姓名" />
          </el-form-item>

          <el-form-item label="新闻分类" prop="category">
            <el-select v-model="form.categoryId" placeholder="请选择分类">
              <el-option
                  v-for="item in categoryOptions"
                  :key="item.category_id"
                  :label="item.category_name"
                  :value="item.category_id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="内容摘要" prop="summary">
            <el-input
                v-model="form.summary"
                type="textarea"
                :rows="3"
                placeholder="请输入内容摘要"
                maxlength="200"
                show-word-limit
            />
          </el-form-item>

          <!-- 富文本编辑器 -->
          <el-form-item label="新闻内容" prop="content">
            <div class="editor-container">
              <QuillEditor
                  ref="myQuillEditor"
                  v-model:content="form.content"
                  contentType="html"
                  :options="editorOptions"
                  class="editor-content"
                  @blur="onEditorBlur"
              />
            </div>
          </el-form-item>


          <el-form-item label="发布时间">
            <el-date-picker
                v-model="form.publishTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-radio-group v-model="form.statusCode">
              <el-radio :label="1">草稿</el-radio>
              <el-radio :label="2">立即发布</el-radio>  <!-- 2是审核状态，后台审核之后状态变成 3已发布  -->
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm">{{ form.statusCode === 1 ? '保存' : '发布' }}</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <!-- 预览区调整为8列 -->
      <el-col :span="8">
        <div class="preview-area">
          <h3 class="preview-title">预览效果</h3>
          <div class="preview-content">
            <h2>{{ form.title || '新闻标题' }}</h2>
            <div class="meta-info">
              <span v-if="form.author" class="author">作者：{{ form.author }}</span>
              <span v-if="form.publishTime" class="publish-time">{{ formatDate(form.publishTime) }}</span>
            </div>
            <div class="summary" v-if="form.summary">{{ form.summary }}</div>
            <div v-html="form.content" class="ql-editor" />
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from '@/utils/request';
import { useAuthStore } from '@/stores/auth'
import { getContentDetailInfo } from '@/api/contents'

// 使用兼容Vue3的富文本编辑器
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import {ElMessage} from "element-plus";

export default {
  components: {
    QuillEditor
  },
  data(){
    return{
      // 当前编辑的新闻ID，如果是新增则为null
      contentId: null,
      //表单数据
      form: {
        contentId: null,
        userId: useAuthStore().user.id,
        title: '',
        author: useAuthStore().user.nickname,
        categoryId: '',
        summary: '',
        content: '<h2>新闻内容标题</h2><p>在此处编辑您的新闻内容...</p>',
        statusType:'content_status',
        statusCode: 1,
        publishTime:new Date()
      },
      // 新闻分类
      categoryOptions:null,
      //表单验证
      rules: {
        title: [{required: true, message: '请输入新闻标题', trigger: 'blur'}],
        author: [{required: true, message: '请输入作者姓名', trigger: 'blur'}],
        categoryId: [{required: true, message: '请选择新闻分类', trigger: 'change'}],
        content: [{
          validator: (rule, value, callback) => {
            // 检查内容是否只有空白字符
            const strippedValue = value.replace(/(<([^>]+)>)/gi, '').trim();
            if (!strippedValue) {
              callback(new Error('请输入新闻内容'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }]
      },
      // 富文本编辑器
      editorOptions:{
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            ['link', 'image', 'video'],
            ['clean']
          ]
        },
        placeholder: '请输入新闻内容...',
        theme: 'snow'
      },
      // 封面预览
      coverPreview :null,
      previewImageUrl:null,
      dialogVisible:false

    }
  },
  methods: {
    // 新闻分类
    category() {
      axios.get("/category/categoriesList"
      ).then((resp) => {
        this.categoryOptions = resp.data.data
        console.log(this.categoryOptions)
      })
      console.log(useAuthStore().user.id)
      console.log(useAuthStore().user.nickname)
    },

    // 加载新闻内容
    async loadContent() {
      console.log("当前内容ID:", this.contentId);
      if (!this.contentId) return;
      try {
        const response = await getContentDetailInfo(this.contentId);
        const responseData = response.data.data
        this.form = {
          contentId: responseData.contentId ,
          title: responseData.title,
          author: responseData.username || '',
          categoryId: responseData.categoryId || '',
          summary: responseData.summary || '',
          content: responseData.content || '',
          statusCode: responseData.statusCode || 1,
          publishTime: responseData.publishTime || new Date()
        };

      } catch (error) {
        console.error('获取内容详情失败:', error);
        this.$message.error(`加载失败: ${error.message}`);
      }
    },
    // 编辑器失焦事件
    onEditorBlur(){
      // 触发内容验证
      this.$refs.formRef.validateField('content');
    },

    // 提交表单（整体验证）
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          console.log('表单验证通过', this.form);

          // 根据 statusCode 动态设置消息模板
          const isDraft = this.form.statusCode === 1; // 1=草稿，2=立即发布
          const successMsg = isDraft ? '保存成功' : '发布成功，等待审核';
          const errorMsgPrefix = isDraft ? '保存失败' : '发布失败';

          // const apiUrl = this.contentId ? "/contents/update" : "/contents/saveOrUpdate";

          axios.post("/contents/saveOrUpdate", this.form)
              .then(response => {
                if (response.data.code === 200) {
                  ElMessage.success(successMsg);
                  this.$router.go(-1);
                } else {
                  ElMessage.error(`${errorMsgPrefix}: ${response.data.message}`);
                }
              })
              .catch(error => {
                ElMessage.error(`${errorMsgPrefix}: ${error.message}`);
              });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },

    //返回
    goBack(){
      this.$router.go(-1);
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },

    // 重置表单
    resetForm(){
      if (this.contentId) {
        // 如果是编辑模式，重置为原始内容
        this.loadContent();
      } else {
        // 如果是新增模式，清空表单
        this.$refs.formRef.resetFields();
        this.form.content = '<h2>新闻内容标题</h2><p>在此处编辑您的新闻内容...</p>';
      }
    },
  },
  created(){
    this.category();
    // 从路由参数中获取新闻ID
    this.contentId = this.$route.params.id || null;
    if (this.contentId) {
      this.loadContent();
    }
  },
}
</script>

<style scoped>
/* 原有样式保持不变 */
.app-container {
  width: 100%;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.editor-container {
  position: relative;
}

.editor-content {
  height: 400px;
  margin-bottom: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.ql-toolbar) {
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

:deep(.ql-container) {
  height: 350px;
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
}

.preview-area {
  margin-top: 40px;
  background: #fff;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.preview-title {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  color: #409eff;
  text-align: center;
  font-size: 18px;
}

.preview-content {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.preview-content h2 {
  color: #303133;
  margin-bottom: 15px;
  font-size: 22px;
}

.cover-preview {
  width: 100%;
  margin-top: 20px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.ql-editor {
  min-height: 300px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background: #fff;
}

.meta-info {
  margin: 20px 0;
  color: #606266;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  padding-bottom: 15px;
  border-bottom: 1px dashed #ebeef5;
}

.summary {
  color: #606266;
  font-size: 15px;
  line-height: 1.8;
  margin: 20px 0;
  padding: 15px;
  background-color: #f0f7ff;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  text-align: center;
}
</style>
